package com.cindata

import grails.converters.JSON
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class RoleMenuController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        respond RoleMenu.list(params), model: [roleMenuCount: RoleMenu.count()]
    }

    def show(RoleMenu roleMenu)
    {
        respond roleMenu
    }

    def create()
    {
        respond new RoleMenu(params)
    }

    @Transactional
    def save(RoleMenu roleMenu)
    {
        if (roleMenu == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (roleMenu.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond roleMenu.errors, view: 'create'
            return
        }

        roleMenu.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'roleMenu.label', default: 'RoleMenu'), roleMenu.id])
                redirect roleMenu
            }
            '*' { respond roleMenu, [status: CREATED] }
        }
    }

    def edit(RoleMenu roleMenu)
    {
        respond roleMenu
    }

    @Transactional
    def update(RoleMenu roleMenu)
    {
        if (roleMenu == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (roleMenu.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond roleMenu.errors, view: 'edit'
            return
        }

        roleMenu.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'roleMenu.label', default: 'RoleMenu'), roleMenu.id])
                redirect roleMenu
            }
            '*' { respond roleMenu, [status: OK] }
        }
    }

    @Transactional
    def delete(RoleMenu roleMenu)
    {

        if (roleMenu == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        roleMenu.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'roleMenu.label', default: 'RoleMenu'), roleMenu.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'roleMenu.label', default: 'RoleMenu'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def getAllRole()
    {
        def user = User.findById(springSecurityService.principal.id)
        def roleSql = "select new map(r.id as id, r.name as name, r.authority as authority) from Role r where 1=1"
        if (!UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            def userRoleList = UserRole.findAllByUser(user)*.role
            def userRoleSql = " ("
            if (userRoleList?.size() > 0)
            {
                userRoleList?.each {
                    userRoleSql += "'" + it?.id + "',"
                }
                userRoleSql = userRoleSql?.substring(0, userRoleSql?.lastIndexOf(",")) + ")"
            }
            roleSql += " and r.id in " + userRoleSql
        }
        def name = params['name']
        if (name)
        {
            roleSql += " and r.name like '%${name}%'"
        }
        roleSql += " order by authority"
        println "roleSql:" + roleSql
        def roleList = Role.executeQuery(roleSql).asList()

        def menuSql = "select new map(m.id as id, m.parent.id as pId, m.title as name) from Menu m where m.status = '1' order by m.orderNum"
        def menuList = Menu.executeQuery(menuSql).asList()

        render([status: "success", roleList: roleList, menuList: menuList] as JSON);
    }

    def queryAllRoleMunuById()
    {
        def id = params["id"]
        def resultList = RoleMenu.findAllByRole(Role.findById(id))

        def roleMenuList = []
        def sql = "select new map(m.id as id, m.parent.id as pId, m.title as name) from Menu m where m.status = '1' order by m.orderNum"
        def menuList = Menu.executeQuery(sql).asList()
        menuList?.each {
            if (it?.id in resultList*.menu.id)
            {
                def item = [id: it?.id, pId: it?.pId, name: it?.name, checked: true, open: true]
                roleMenuList.add(item)
            }
            else
            {
                def item = [id: it?.id, pId: it?.pId, name: it?.name, checked: false, open: true]
                roleMenuList.add(item)
            }
        }

        render([status: "success", roleMenuList: roleMenuList] as JSON)
    }

    @Transactional
    def addRoleMenu()
    {
        def roleId = params["roleId"]
        def menuId = params["menuId"]
        def flag = params["flag"]

        def role = Role.findById(roleId)
        def menu = Menu.findById(menuId)

        if (!roleId || !role)
        {
            render([status: "failed", message: "更新失败"] as JSON)
            return
        }

        if (!menuId || !menu)
        {
            render([status: "failed", message: "更新失败"] as JSON)
            return
        }

        if (flag == "true")
        {
            // 添加权限
            def roleMenu = new RoleMenu()
            roleMenu.role = role
            roleMenu.menu = menu
            roleMenu.save flush: true

            render([status: "success"] as JSON);
        }
        else
        {
            // 删除权限
            def roleMenu = RoleMenu.findByRoleAndMenu(role, menu)
            roleMenu?.delete flush: true

            render([status: "success"] as JSON)
        }
    }

    def queryRoleById()
    {
        def id = params["id"]
        def role = Role.findById(id)
        render([status: "success", role: role] as JSON)
    }

    @Transactional
    def saveRole(Role role)
    {
        if (role == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (role.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond role.errors, view: 'index'
            return
        }

        role.save flush: true

        redirect action: 'index'
    }

    @Transactional
    def deleteRoleMemu()
    {
        def user = User.findById(springSecurityService.principal.id)
        if (!UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            render([status: "failed", message: "对不起，您没有操作权限"] as JSON)
            return
        }

        def roleId = params["roleId"]
        def role = Role.findById(roleId)
        if (role?.authority != "ROLE_ADMINISTRATOR")
        {
            if (UserRole.findByRole(role))
            {
                render([status: "failed", message: "对不起，请先删除该角色下用户"] as JSON)
                return
            }
            else
            {
                def roleMenuList = RoleMenu.findAllByRole(role)
                roleMenuList?.each {
                    it?.delete flush: true
                }
                role.delete flush: true

                render([status: "success"] as JSON)
                return
            }
        }
        else
        {
            render([status: "failed", message: "对不起，管理员角色不允许删除"] as JSON)
            return
        }
    }
}
